package service;

import com.thoughtworks.xstream.XStream;
import entity.AccessToken;
import entity.BaseMessage;
import entity.TextMessage;
import net.sf.json.JSONObject;
import netscape.javascript.JSObject;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import util.Util;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

public class Service {
    private  static  final String TOKEN="zbc";
    private  static  final  String GET_TOKEN_URL="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
    private  static  final  String APPID="wx305db0dd2edf73ea";
    private  static  final  String APPSECRET="c2e2153d4799068f70ff2687227800e0";
    private static AccessToken at;
    //获取token
    private static void getToken(){
        String url=GET_TOKEN_URL.replace("APPID",APPID).replace("APPSECRET",APPSECRET);
        String tokenStr=Util.get(url);
        JSONObject jsObject=JSONObject.fromObject(tokenStr);
        String token=jsObject.getString("access_token");
        String expireIn=jsObject.getString("expires_in");
        at=new AccessToken(token,expireIn);
    }
    public static  String getAccessToken(){
        if (at==null|| at.isExpired()){
            getToken();
        }
        return  at.getAccessToken();
    }
    public static boolean check(String timestamp,String nonce,String signature){
        String[] strs=new String[]{TOKEN,timestamp,nonce};
        Arrays.sort(strs);
        String str=strs[0]+strs[1]+strs[2];
        String mysig=sha1(str);
        return mysig.equalsIgnoreCase(signature);
    }
    public  static  String sha1(String src)  {
        try {
            MessageDigest md = MessageDigest.getInstance("sha1");
            byte[] digest = md.digest(src.getBytes());
            char[] chars={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
            StringBuilder sb=new StringBuilder();
            for (byte b:digest){
                sb.append(chars[(b>>4)&15]);
                sb.append(chars[b&15]);
            }
           return sb.toString();

        }catch (NoSuchAlgorithmException e){
            e.printStackTrace();
        }
        return null;
    }
    //解析XML数据包
   public static Map<String, String> parseRequest(InputStream is) {
        Map<String,String> map=new HashMap<>();
        SAXReader reader=new SAXReader();
        try{
            //读取输入流，获取文档对象
            Document document=reader.read(is);
            //根据文档对象获取根节点
            Element root = document.getRootElement();
            List<Element> elements=root.elements();
            for (Element e:elements){
                map.put(e.getName(),e.getStringValue());
            }
        } catch (DocumentException e){
            e.printStackTrace();;
        }
        return map;
    }
    //处理事件和消息回复，返回xml数据包
    public static String getRespose(Map<String, String> requestMap) {
        BaseMessage msg=null;
        String msgType=requestMap.get("MsgType");
        switch (msgType){
            case "text":
                msg=dealTextMessage(requestMap);
                break;
            case "image":break;
            case "voice":break;
            case "video":break;
            case "shortvideo":break;
            case "location":break;
            case "link":break;
            case "event":
                msg=dealEvent(requestMap);
        }
        //把消息对象处理为xml数据包
        if(msg!=null) {
            //System.out.println(msg);
            return beanToXml(msg);
        }
        return null;
    }
    public static String beanToXml(BaseMessage msg) {
        XStream stream=new XStream();
        stream.processAnnotations(TextMessage.class);
        String xml=stream.toXML(msg);
        return  xml;
    }
    private static  BaseMessage dealEvent(Map<String,String> requestMap){
        String event=requestMap.get("Event");
        switch (event){
            case "CLICK":
                return  dealClick(requestMap);

            case "VIEW":
                return dealView(requestMap);

        }
        return  null;
    }
    //处理click菜单
    private static BaseMessage dealClick(Map<String,String> requestMap){
        String key=requestMap.get("EventKey");
        switch (key){
            case "1":
                return new TextMessage(requestMap,"你点了一级菜单");

            case "32":break;

        }
        return  null;

    }
    //处理view菜单
    private static BaseMessage dealView(Map<String,String> requestMap){
        return  null;

    }
    private static BaseMessage dealTextMessage(Map<String,String> requestMap){
        String msg=requestMap.get("Content");


        TextMessage tm=new TextMessage(requestMap,"看看");

        return  tm;
    }
}
